#include "Terrain.h"
#include <SDL.h>

Terrain::Terrain(std::string fileName, float xScale, float yScale, float zScale)
{
	heights.clear();
	width = 0;
	length = 0;
	sx = xScale;
	sy = yScale;
	sz = zScale;

	load(fileName);
}

void * Terrain::data()
{
	return &heights[0];
}

Terrain::~Terrain(void)
{
}

void Terrain::render()
{
	glPushMatrix();
	glCallList(terrainId);
	glPopMatrix();
}

void Terrain::load(std::string fileName)
{
	SDL_Surface* img = SDL_LoadBMP(fileName.c_str());

	width = img->w;
	length = img->h;

	for(int i=0;i<img->h;i++)
	{
		for(int j=0;j<img->w;j++)
		{
			Uint32 pixel=((Uint32*)img->pixels)[i*img->pitch/4 + j];
			Uint8 r,g,b;	//unsigned char
			SDL_GetRGB(pixel,img->format,&r,&g,&b);
			heights.push_back((float)r/255.f);
		}
	}

	float px = -width/2.f;
	float pz = -length/2.f;

	terrainId = glGenLists(1);

	glNewList(terrainId, GL_COMPILE);

	for(int i=0; i<length-1; i++)
	{
		for(int j=0; j<width-1; j++)
		{
			glBegin(GL_TRIANGLES);
				glColor3f( heights[i*width+j] + 0.2, 
					heights[i*width+j] + 0.2, 
					heights[i*width+j] + 0.2);

				glVertex3f(sx*(i+px),	sy*(heights[i*width+j]),			sz*(j+pz));
				glVertex3f(sx*(i+1+px),	sy*(heights[(i+1)*width+j]),		sz*(j+pz));
				glVertex3f(sx*(i+1+px),	sy*(heights[(i+1)*width+(j+1)]),	sz*(j+1+pz));
				
				glVertex3f(sx*(i+px),	sy*(heights[i*width+j]),			sz*(j+pz));
				glVertex3f(sx*(i+1+px),	sy*(heights[(i+1)*width+j+1]),		sz*(j+1+pz));
				glVertex3f(sx*(i+px),	sy*(heights[i*width+(j+1)]),		sz*(j+1+pz));
			glEnd();
		}
	}

	glEndList();
}
